/*
 * @Author: xiaosihan
 * @Date: 2025-08-24 10:00:00
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-24 10:00:00
 */
import { useState, useEffect } from 'react';
import styles from './mysqlEventManager.module.less';
import mysqlEventApi from '@/api/mysqlEventApi';

// 事件类型定义
interface MySqlEvent {
    Db: string;
    Name: string;
    Body: string;
    Definer: string;
    ExecuteAt: string;
    IntervalField: string;
    IntervalValue: string;
    Created: string;
    Status: 'ENABLED' | 'DISABLED' | 'SLAVESIDE_DISABLED';
    OnCompletion: string;
    Originator: number;
    CharacterSetClient: string;
    CollationConnection: string;
    DatabaseCollation: string;
}

// 事件调度器状态
interface EventSchedulerStatus {
    event_scheduler: 'ON' | 'OFF' | 'DISABLED';
}

const MySqlEventManager = () => {
    // 状态管理
    const [events, setEvents] = useState<MySqlEvent[]>([]);
    const [eventSchedulerStatus, setEventSchedulerStatus] = useState<EventSchedulerStatus | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [activeTab, setActiveTab] = useState<'oneTime' | 'recurring'>('oneTime');
    const [showCreateForm, setShowCreateForm] = useState(false);

    // 一次性事件表单数据
    const [oneTimeEventData, setOneTimeEventData] = useState({
        eventName: '',
        sqlStatement: '',
        executeAt: ''
    });

    // 周期性事件表单数据
    const [recurringEventData, setRecurringEventData] = useState({
        eventName: '',
        sqlStatement: '',
        startTime: '',
        intervalValue: 1,
        intervalUnit: 'DAY',
        endTime: '',
        comment: ''
    });

    // 间隔单位选项
    const intervalUnits = [
        'SECOND', 'MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'QUARTER', 'YEAR'
    ];

    // 加载事件数据
    const loadEvents = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const response = await mysqlEventApi.event_events();
            if (response && response.data) {
                setEvents(response.data);
            }
        } catch (err) {
            setError('加载事件列表失败: ' + (err instanceof Error ? err.message : String(err)));
        } finally {
            setIsLoading(false);
        }
    };

    // 加载事件调度器状态
    const loadEventSchedulerStatus = async () => {
        try {
            const response = await mysqlEventApi.event_status();
            if (response && response.data) {
                setEventSchedulerStatus(response.data);
            }
        } catch (err) {
            setError('加载事件调度器状态失败: ' + (err instanceof Error ? err.message : String(err)));
        }
    };

    // 切换事件调度器状态
    const toggleEventScheduler = async (start: boolean) => {
        setIsLoading(true);
        setError(null);
        try {
            if (start) {
                await mysqlEventApi.event_start_scheduler();
            } else {
                await mysqlEventApi.event_stop_scheduler();
            }
            await loadEventSchedulerStatus();
            await loadEvents();
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            // 特殊处理权限错误
            if (errorMessage.includes('SUPER') || errorMessage.includes('SYSTEM_VARIABLES_ADMIN')) {
                setError(`操作失败: 需要SUPER或SYSTEM_VARIABLES_ADMIN权限才能修改事件调度器状态。请联系数据库管理员获取相应权限。`);
            } else {
                setError(`操作失败: ${errorMessage}`);
            }
        } finally {
            setIsLoading(false);
        }
    };

    // 创建一次性事件
    const handleCreateOneTimeEvent = async () => {
        if (!oneTimeEventData.eventName || !oneTimeEventData.sqlStatement || !oneTimeEventData.executeAt) {
            setError('请填写所有必填字段');
            return;
        }

        setIsLoading(true);
        setError(null);
        try {
            await mysqlEventApi.event_create_one_time(oneTimeEventData);

            // 重置表单
            setOneTimeEventData({
                eventName: '',
                sqlStatement: '',
                executeAt: ''
            });
            setShowCreateForm(false);
            await loadEvents();
        } catch (err) {
            setError(`创建事件失败: ${err instanceof Error ? err.message : String(err)}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 创建周期性事件
    const handleCreateRecurringEvent = async () => {
        if (!recurringEventData.eventName || !recurringEventData.sqlStatement || !recurringEventData.startTime) {
            setError('请填写所有必填字段');
            return;
        }

        setIsLoading(true);
        setError(null);
        try {
            await mysqlEventApi.event_create_recurring(recurringEventData);

            // 重置表单
            setRecurringEventData({
                eventName: '',
                sqlStatement: '',
                startTime: '',
                intervalValue: 1,
                intervalUnit: 'DAY',
                endTime: '',
                comment: ''
            });
            setShowCreateForm(false);
            await loadEvents();
        } catch (err) {
            setError(`创建事件失败: ${err instanceof Error ? err.message : String(err)}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 切换事件状态（启用/禁用）
    const toggleEventStatus = async (eventName: string, enable: boolean) => {
        setIsLoading(true);
        setError(null);
        try {
            if (enable) {
                await mysqlEventApi.event_enable({ eventName });
            } else {
                await mysqlEventApi.event_disable({ eventName });
            }
            await loadEvents();
        } catch (err) {
            setError(`操作失败: ${err instanceof Error ? err.message : String(err)}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 删除事件
    const handleDeleteEvent = async (eventName: string) => {
        if (!window.confirm(`确定要删除事件 ${eventName} 吗？`)) {
            return;
        }

        setIsLoading(true);
        setError(null);
        try {
            await mysqlEventApi.event_drop({ eventName });
            await loadEvents();
        } catch (err) {
            setError(`删除失败: ${err instanceof Error ? err.message : String(err)}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 组件挂载时加载数据
    useEffect(() => {
        loadEvents();
        loadEventSchedulerStatus();
    }, []);

    return (
        <div className={styles.content}>
            <h1 className={styles.title}>MySQL 事件调度管理</h1>

            {/* 错误信息显示 */}
            {error && (
                <div className={styles.error}>
                    {error}
                </div>
            )}

            {/* 事件调度器状态控制 */}
            <div className={styles.schedulerStatus}>
                <h2>事件调度器状态</h2>
                <div className={styles.statusInfo}>
                    <span className={`statusBadge ${eventSchedulerStatus?.event_scheduler === 'ON' ? 'enabled' : 'disabled'}`}>
                        {eventSchedulerStatus?.event_scheduler || '未知'}
                    </span>
                    <div className={styles.statusActions}>
                        {eventSchedulerStatus?.event_scheduler !== 'ON' ? (
                            <button
                                className={styles.btnPrimary}
                                onClick={() => toggleEventScheduler(true)}
                                disabled={isLoading}
                                title="需要SUPER或SYSTEM_VARIABLES_ADMIN权限"
                            >
                                开启事件调度器
                            </button>
                        ) : (
                            <button
                                className={styles.btnDanger}
                                onClick={() => toggleEventScheduler(false)}
                                disabled={isLoading}
                                title="需要SUPER或SYSTEM_VARIABLES_ADMIN权限"
                            >
                                关闭事件调度器
                            </button>
                        )}
                    </div>
                </div>
                <div className={styles.permissionNote}>
                    注意：修改事件调度器状态需要SUPER或SYSTEM_VARIABLES_ADMIN权限
                </div>
            </div>

            {/* 事件列表 */}
            <div className={styles.eventsSection}>
                <div className={styles.sectionHeader}>
                    <h2>事件列表</h2>
                    <button
                        className={styles.btnPrimary}
                        onClick={() => setShowCreateForm(true)}
                        disabled={isLoading || eventSchedulerStatus?.event_scheduler !== 'ON'}
                    >
                        创建新事件
                    </button>
                </div>

                {isLoading ? (
                    <div className={styles.loading}>加载中...</div>
                ) : (
                    <div className={styles.eventsTableContainer}>
                        <table className={styles.eventsTable}>
                            <thead>
                                <tr>
                                    <th>事件名称</th>
                                    <th>数据库</th>
                                    <th>状态</th>
                                    <th>执行时间</th>
                                    <th>间隔</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {events.length === 0 ? (
                                    <tr>
                                        <td colSpan={6} className={styles.emptyRow}>暂无事件</td>
                                    </tr>
                                ) : (
                                    events.map((event) => (
                                        <tr key={`${event.Db}_${event.Name}`}>
                                            <td className={styles.eventName}>{event.Name}</td>
                                            <td>{event.Db}</td>
                                            <td>
                                                <span className={`statusBadge ${event.Status === 'ENABLED' ? 'enabled' : 'disabled'}`}>
                                                    {event.Status}
                                                </span>
                                            </td>
                                            <td>{event.ExecuteAt || '立即'}</td>
                                            <td>{event.IntervalValue ? `${event.IntervalValue} ${event.IntervalField}` : '一次性'}</td>
                                            <td className={styles.actions}>
                                                {event.Status === 'ENABLED' ? (
                                                    <button
                                                        className={styles.btnSecondary}
                                                        onClick={() => toggleEventStatus(event.Name, false)}
                                                        disabled={isLoading}
                                                    >
                                                        禁用
                                                    </button>
                                                ) : (
                                                    <button
                                                        className={styles.btnPrimary}
                                                        onClick={() => toggleEventStatus(event.Name, true)}
                                                        disabled={isLoading}
                                                    >
                                                        启用
                                                    </button>
                                                )}
                                                <button
                                                    className={styles.btnDanger}
                                                    onClick={() => handleDeleteEvent(event.Name)}
                                                    disabled={isLoading}
                                                >
                                                    删除
                                                </button>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* 创建事件表单弹窗 */}
            {showCreateForm && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h2>创建新事件</h2>
                            <button
                                className={styles.closeButton}
                                onClick={() => setShowCreateForm(false)}
                            >
                                ×
                            </button>
                        </div>

                        <div className={styles.tabs}>
                            <button
                                className={`tabButton ${activeTab === 'oneTime' ? 'active' : ''}`}
                                onClick={() => setActiveTab('oneTime')}
                            >
                                一次性事件
                            </button>
                            <button
                                className={`tabButton ${activeTab === 'recurring' ? 'active' : ''}`}
                                onClick={() => setActiveTab('recurring')}
                            >
                                周期性事件
                            </button>
                        </div>

                        <div className={styles.formContent}>
                            {activeTab === 'oneTime' ? (
                                <div className={styles.formGroup}>
                                    <div className={styles.formItem}>
                                        <label>事件名称 *</label>
                                        <input
                                            type="text"
                                            value={oneTimeEventData.eventName}
                                            onChange={(e) => setOneTimeEventData({ ...oneTimeEventData, eventName: e.target.value })}
                                            placeholder="请输入事件名称"
                                        />
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>SQL语句 *</label>
                                        <textarea
                                            value={oneTimeEventData.sqlStatement}
                                            onChange={(e) => setOneTimeEventData({ ...oneTimeEventData, sqlStatement: e.target.value })}
                                            placeholder="请输入要执行的SQL语句"
                                            rows={4}
                                        />
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>执行时间 *</label>
                                        <input
                                            type="datetime-local"
                                            value={oneTimeEventData.executeAt}
                                            onChange={(e) => setOneTimeEventData({ ...oneTimeEventData, executeAt: e.target.value })}
                                        />
                                    </div>
                                </div>
                            ) : (
                                <div className={styles.formGroup}>
                                    <div className={styles.formItem}>
                                        <label>事件名称 *</label>
                                        <input
                                            type="text"
                                            value={recurringEventData.eventName}
                                            onChange={(e) => setRecurringEventData({ ...recurringEventData, eventName: e.target.value })}
                                            placeholder="请输入事件名称"
                                        />
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>SQL语句 *</label>
                                        <textarea
                                            value={recurringEventData.sqlStatement}
                                            onChange={(e) => setRecurringEventData({ ...recurringEventData, sqlStatement: e.target.value })}
                                            placeholder="请输入要执行的SQL语句"
                                            rows={4}
                                        />
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>开始时间 *</label>
                                        <input
                                            type="datetime-local"
                                            value={recurringEventData.startTime}
                                            onChange={(e) => setRecurringEventData({ ...recurringEventData, startTime: e.target.value })}
                                        />
                                    </div>
                                    <div className={styles.formRow}>
                                        <div className={styles.formItemHalf}>
                                            <label>间隔值 *</label>
                                            <input
                                                type="number"
                                                min="1"
                                                value={recurringEventData.intervalValue}
                                                onChange={(e) => setRecurringEventData({ ...recurringEventData, intervalValue: parseInt(e.target.value) || 1 })}
                                            />
                                        </div>
                                        <div className={styles.formItemHalf}>
                                            <label>间隔单位 *</label>
                                            <select
                                                value={recurringEventData.intervalUnit}
                                                onChange={(e) => setRecurringEventData({ ...recurringEventData, intervalUnit: e.target.value })}
                                            >
                                                {intervalUnits.map(unit => (
                                                    <option key={unit} value={unit}>{unit}</option>
                                                ))}
                                            </select>
                                        </div>
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>结束时间（可选）</label>
                                        <input
                                            type="datetime-local"
                                            value={recurringEventData.endTime}
                                            onChange={(e) => setRecurringEventData({ ...recurringEventData, endTime: e.target.value })}
                                        />
                                    </div>
                                    <div className={styles.formItem}>
                                        <label>备注（可选）</label>
                                        <input
                                            type="text"
                                            value={recurringEventData.comment}
                                            onChange={(e) => setRecurringEventData({ ...recurringEventData, comment: e.target.value })}
                                            placeholder="请输入备注信息"
                                        />
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className={styles.modalFooter}>
                            <button
                                className={styles.btnSecondary}
                                onClick={() => setShowCreateForm(false)}
                                disabled={isLoading}
                            >
                                取消
                            </button>
                            <button
                                className={styles.btnPrimary}
                                onClick={activeTab === 'oneTime' ? handleCreateOneTimeEvent : handleCreateRecurringEvent}
                                disabled={isLoading}
                            >
                                {isLoading ? '创建中...' : '创建事件'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default MySqlEventManager;
